package com.syty.demo.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.Property;
import org.springframework.jdbc.datasource.embedded.DataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * Druid连接池工具类
 */
@Api(tags = "Druid连接池工具类",value = "创建、释放")
public class JDBCUtils {

    @Autowired
    private static DataSource dataSource;

    static {

        try {
            //加载配置文件
            Properties properties = new Properties();
            properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
//            获取数据源
            DataSource source = DruidDataSourceFactory.createDataSource(properties);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

//    获取链接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

//    释放资源
    public static void close(ResultSet rs,Statement statement, Connection connection) throws SQLException {
        try {
            if (rs!=null){
                rs.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

//    获取数据源
    public static DataSource getDataSource() {
        return dataSource;
    }
}
